<template>
  <div style="width: 100%;display: flex;justify-content: center">
    <div style="width: 33%"><span>{{lineTitle}}</span></div>
    <div style="width: 33%"><span>{{cloTitle}}</span></div>
    <div style="width: 33%"><span>{{burndownTitle}}</span></div>
  </div>

  <div class="charts-container">
    <!-- 每日任务完成与截止情况(折线图) -->
    <div class="chart-box">
      <canvas id="lineChart" width="400" height="400"></canvas>
    </div>


    <!-- 每日工作的员工数量(柱形图) -->
    <div class="chart-box">
      <canvas id="mixedChart" width="400" height="400"></canvas>
    </div>

    <!-- 燃尽图 -->
    <div class="chart-box">
      <canvas id="burndownChart" width="400" height="400"></canvas>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch} from 'vue';
import { Chart, LineController, BarController, CategoryScale, LinearScale, PointElement, LineElement, BarElement, Title, Tooltip, Legend } from 'chart.js';
import {useUserStore} from "../../../stores/UserStore.ts";
import {getCloChartData, getLineDataAsync} from "../../../api/Report/projectData.ts";
import {ElMessage} from "element-plus";

const tenantId = useUserStore().userInfo.tenantId;


const lineTitle="每日任务完成与截止情况"

Chart.register(
    LineController,
    BarController,
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    BarElement,
    Title,
    Tooltip,
    Legend
);

// 数据
const lineData = ref<any>({});
const lineData1 = ref<any>({});
const lineData2 = ref<any>({});
const mixedData = ref<any>({});
const burndownData = ref<any>({});
const projects=ref(['项目A', '项目B', '项目C'])

// 图表实例（方便更新销毁）
let lineChart: Chart | null = null;
let mixedChart: Chart | null = null;
let burndownChart: Chart | null = null;

// 折线图
const getLineChartData=async ()=>{
  const res=await getLineDataAsync(tenantId);
  console.log(res)
  for(let i=0; i<res.length; i++){
    lineData1.value[i]=res[i].dueWorkCount
    lineData2.value[i]=res[i].finishWorkCount
  }
  lineLabelFunc()
}
getLineChartData()
//折线图数据
const lineLabel:any=[]
const lineLabelFunc=()=>{
  for(let i=0; i<22; i++){
    lineLabel[i]=(i+1).toString()
  }
}
lineData.value={
  line:{
    label:lineLabel,
    datasets:[
      {
        label:'当天完成',
        data:lineData1.value,
        fill: false,
        borderColor:'rgba(255, 99, 132, 1)',
        tension: 0.1,
      },
      {
        label: '当天截止',
        data:lineData2.value,
        fill: false,
        borderColor:'rgba(75, 192, 192, 1)',
        tension: 0.1,
      }
    ]
  }
}
//柱形图数据
const cloTitle="每日工作的员工数量"
const cloLabel=[]
const cloData=ref<any>([])
const getCloChartDataAsync=async ()=>{
  const res= await getCloChartData(tenantId)
  if(res.length==0){
    ElMessage.error("无数据")
    return
  }
  for(let i=0; i<res.length; i++){
    cloLabel[i]=(i+1).toString()
    if(i==3){
      cloLabel[i]=(i+1).toString()+"(今天)"
    }
    cloData.value[i]=res[i].workStaff
  }
}
getCloChartDataAsync()
mixedData.value={
  mixed:{
    labels:cloLabel,
    datasets: [{
      label:"柱形图",
      data:cloData.value,
      fill: false,
      backgroundColor:'rgba(255, 99, 132, 0.5)',
      borderColor: 'rgba(255, 99, 132, 1)',
      tension: 0.1,
    }]
  }
}


//燃尽图数据
const burndownTitle="项目燃尽图"
/* const planWorkData=ref<any>({});
const actualWorkData=ref<any>({});
const expectedWorkData=ref<any>({});
const getBurndownChartData=async ()=>{
  const res=await getBurndownData(tenantId)
  if(res==null){
    ElMessage.error("无数据")
  }

}

const burndownChartData=ref({
  burndown: {
    labels: ['第1天', '第2天', '第3天', '第4天', '第5天', '第6天'],
    datasets: [
      {
        label: '计划曲线',
        data: planWorkData,
        borderColor: 'rgba(75, 192, 192, 1)',
        fill: false,
        tension: 0.1,
        borderDash: [5, 5],
      },
      {
        label: '实际曲线',
        data: actualWorkData,
        borderColor: 'rgba(255, 99, 132, 1)',
        fill: false,
        tension: 0.1,
      },
      {
        label: '预测曲线',
        data: expectedWorkData,
        borderColor: 'rgba(54, 162, 235, 1)',
        fill: false,
        tension: 0.1,
        borderDash: [10, 5],
      },
    ],
  },
}); */

async function fetchData() {
  // 模拟异步数据请求
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        burndown: {
          labels: ['第1天', '第2天', '第3天', '第4天', '第5天', '第6天'],
          datasets: [
            {
              label: '计划曲线',
              data: [50, 45, 40, 35, 30, 25],
              borderColor: 'rgba(75, 192, 192, 1)',
              fill: false,
              tension: 0.1,
              borderDash: [5, 5],
            },
            {
              label: '实际曲线',
              data: [50, 43, 37, 28, 20, 10],
              borderColor: 'rgba(255, 99, 132, 1)',
              fill: false,
              tension: 0.1,
            },
            {
              label: '预测曲线',
              data: [50, 44, 38, 32, 26, 20],
              borderColor: 'rgba(54, 162, 235, 1)',
              fill: false,
              tension: 0.1,
              borderDash: [10, 5],
            },
          ],
        },
      });
    }, 500);
  });
}

// 初始化图表
function initChart(id:any, type:any, data:any, options:any) {
  const canvas = document.getElementById(id) as HTMLCanvasElement;
  if (canvas) {
    const ctx = canvas.getContext('2d');
    if (ctx) {
      return new Chart(ctx, { type, data, options });
    }
  }
  return null;
}

// 监听数据变化
watch([lineData, mixedData, burndownData], ([newLineData, newMixedData, newBurndownData]) => {
  // 渲染折线图
  if (newLineData && Object.keys(newLineData).length) {
    if (lineChart) lineChart.destroy();
    lineChart = initChart('lineChart', 'line', newLineData, {
      responsive: true,
      scales: { x: { beginAtZero: true }, y: { beginAtZero: true } },
    });
  }

  // 渲染混合图表
  if (newMixedData && Object.keys(newMixedData).length) {
    if (mixedChart) mixedChart.destroy();
    mixedChart = initChart('mixedChart', 'bar', newMixedData, {
      responsive: true,
      scales: { x: { beginAtZero: true }, y: { beginAtZero: true } },
    });
  }

  // 渲染燃尽图
  if (newBurndownData && Object.keys(newBurndownData).length) {
    if (burndownChart) burndownChart.destroy();
    burndownChart = initChart('burndownChart', 'line', newBurndownData, {
      responsive: true,
      scales: {
        x: { beginAtZero: true },
        y: { beginAtZero: true, max: 50 },
      },
    });
  }
});
// 获取数据
fetchData().then((data: any) => {
  lineData.value=lineData.value.line
  mixedData.value=mixedData.value.mixed
  burndownData.value = data.burndown;
});
</script>

<style scoped>
.charts-container {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.chart-box {
  width: 30%;
  display: flex;
  justify-content: center;
}
</style>
